package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"mime/multipart"
	"net/http"
	"path/filepath"
	"image-server/common"
)


type BindFile struct {
	Name  string                `form:"name" binding:"required"`
	Email string                `form:"email" binding:"required"`
	File  *multipart.FileHeader `form:"file" binding:"required"`
}

func setupRouter() *gin.Engine {
	r := gin.Default()
	r.MaxMultipartMemory = 8 << 20 // 8 MiB
	r.StaticFile("/", "./public/index.html")
	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong")
	})
	images := r.Group("/images", gin.BasicAuth(gin.Accounts{
		"admin": "615b1d59680aa4586c4673c534678d17", // user:admin 615b1d59680aa4586c4673c534678d17:bar
	}))
	images.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong")
	})
	images.POST("/upload", func(c *gin.Context) {
		var bindFile BindFile

		// Bind file
		if err := c.ShouldBind(&bindFile); err != nil {
			c.String(http.StatusBadRequest, fmt.Sprintf("err: %s", err.Error()))
			return
		}

		// Save uploaded file
		file := bindFile.File
		dst := filepath.Base(file.Filename)
		basfile,_ := filepath.Abs(common.BaseUploadFilePath)
		fmt.Println("basfile",basfile)
		fmt.Println(dst)
		if err := c.SaveUploadedFile(file, dst); err != nil {
			c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
			return
		}

		c.String(http.StatusOK, fmt.Sprintf("File %s uploaded successfully with fields name=%s and email=%s.", file.Filename, bindFile.Name, bindFile.Email))
	})
	return r
}
func main() {
	r := setupRouter()
	r.Run(":8000")
}
